<template>
  <div class="wh-100" style="background-color: white">
    <div class="w-100 h-7 d-flex-between-center  bor-base-b">
      <div class="d-flex-align-center h-100 ">
        <div v-for="(item,index) in topTitle" :key="index" class="ml-20 d-flex-align-center fs-14 h-100 cursor-pointer"
             :class="{'itemActive':item.isActive,'itemNotActive':!item.isActive}" @click="handleClick(index)">
          {{ item.title }}
        </div>
      </div>
      <div v-if="topTitle[0].isActive" class="mr-12">
        <Input class="w-35" v-model="auditNumberName" placeholder="按单位名称查找"></Input>
        <Button type="primary" size="default"
                @click="handleSearch" class="ml-0 vertical-align-bottom search-btn">搜索
        </Button>
        <Button v-loading="exportingAll" @click="exportDataAuditNumber">导出全部数据</Button>
        <Button v-if="userInfo.resource == 1" type="primary" @click="modalPrewarningValue = true">添加预警值</Button>
      </div>
      <div v-if="topTitle[1].isActive" class="mr-12">
        <Input class="w-35" v-model="auditWarningName" placeholder="按单位名称查找"></Input>
        <Button type="primary" size="default"
                @click="handleSearch" class="ml-0 vertical-align-bottom  search-btn">搜索
        </Button>
        <Button v-loading="exportingAll" @click="exportDataAuditWarning">导出全部数据</Button>
        <Button v-if="userInfo.resource == 1" type="primary" @click="modalEarlyWarningKeywords = true">设置预警关键词
        </Button>
      </div>
      <div v-if="topTitle[2].isActive" class="mr-12">
        <Button v-if="userInfo.resource == 1" type="primary" @click="mobilePrewarningValue = true">设置手机号预警值
        </Button>
      </div>
    </div>
    <div class="w-100 h-92 ">
      <div class="w-100 h-90 mt-12 " v-ref-height="refHeight" v-loading="tableLoading">
        <Table
            :columns="tableColumns"
            :data="tableData"
            :height="refHeight.value"
        >
          <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" @click="checkInfo(row)">查看</Button>
          </template>

        </Table>
      </div>
      <div class="w-100 h-7  d-flex-align-center mt-12">
        <Page
            :total="pages.total"
            :page-size="pages.pageSize"
            :current="pages.pageNumber"
            @on-change="changePage"
            @on-page-size-change="changePageSize"
            show-total
            show-elevator
            show-sizer
            class-name="d-flex-center"
            size="small"
        />
      </div>
    </div>

    <Modal v-model="modalPrewarningValue"
           title="添加预警值"
           width="500">
      <div class="w-100">
        <Form ref="prewarningValueForm" :model="formPrewarningValue" :label-width="labelWidth140">
          <FormItem label="设置省级预警值">
            <InputNumber :min="0" v-model="formPrewarningValue.province"></InputNumber>
          </FormItem>
          <FormItem label="省级是否开启白名单" class="">
            <div class="d-flex-align-center">
              <i-switch v-model="formPrewarningValue.isWhitelist" :true-value="1" :false-value="0" size="large">
                <span slot="open">开启</span>
                <span slot="close">关闭</span>
              </i-switch>
              <div class="fs-14 d-flex-align-center pl-12">
                <div>还没有白名单,</div>
                <div style="color: #2873f3;cursor: pointer;" @click="setWhiteList">去设置白名单</div>
              </div>
            </div>

          </FormItem>
          <FormItem label="设置校级预警值">
            <InputNumber :min="0" v-model="formPrewarningValue.school"></InputNumber>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="modalPrewarningValue = false">取消</Button>
        <Button v-loading="loadingPrewarning" @click="submitFormPrewarningValue" type="primary">确定</Button>
      </div>
    </Modal>

    <Modal v-model="mobilePrewarningValue"
           title="设置手机号预警值"
           width="500">
      <div class="w-100">
        <Form :label-width="labelWidth140">

          <FormItem label="设置手机号预警值">
            <InputNumber :min="0" v-model="mobileThresholdProvince"></InputNumber>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="mobilePrewarningValue = false">取消</Button>
        <Button v-loading="loadingPrewarning" @click="submitMobileValue" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal v-model="modalEarlyWarningKeywords"
           title="添加预警关键词"
           @on-visible-change="notShowModal"
           width="500">
      <div style="color: rgb(55, 140, 254)">
        已保存的预警词：
      </div>
      <div class="w-100 earlyWarningKeywordsStyle overflow-auto-hidden" v-loading="loadingDivEarlyWarningKeywords">
        <Tag v-for="(item,index) in earlyWarningKeywordsList" :key="index" closable @on-close="handleClose(item)">
          {{ item.word }}
        </Tag>
      </div>
      <div slot="footer">
        <Alert v-if="showAlert" type="error" show-icon closable style="text-align: left" @on-close="showAlert=false">
          {{ errorMsg }}
        </Alert>
        <Form ref="earlyWarningKeywordsForm" :model="formEarlyWarningKeywords">
          <FormItem>
            <Input v-model="formEarlyWarningKeywords.alert" type="textarea" :autosize="{minRows: 3,maxRows: 5}"
                   @on-keyup="formEarlyWarningKeywords.alert=formEarlyWarningKeywords.alert.replace(/，|,|\r\n|\n|\r/g,',')"
                   placeholder="请填写关键词，可以填写多个预警关键词，用英文逗号（,）隔开" />
          </FormItem>
        </Form>
        <div class="w-100 mt-8">
          <Button v-loading="loadingEarlyWarningKeywords" @click="addEarlyWarningKeywordsData" type="primary">保存
          </Button>

          <Button @click="modalEarlyWarningKeywords = false">取消</Button>
        </div>
      </div>
    </Modal>

  </div>
</template>

<script>
import Cookies from 'js-cookie';
import {
  addEarlyWarningKeywordsData,
  deleteWordsEarlyWarningKeywordsData,
  editProfileData,
  exportDataAudit,
  exportDataAuditNumber,
  exportDataAuditWarning,
  getAllWordsEarlyWarningKeywordsData,
  getMobileWarningKeywordsData,
  getPageDataAuditData,
  getProfileData,
  getWordsEarlyWarningKeywordsData, submitMobileValue
} from '../../api/dataVerification/dataVerification';
import { updateVal } from '../../util/ObjectUtil';

export default {
  data() {
    return {
      labelWidth140: 140,
      auditNumberName: '',
      auditWarningName: '',
      topTitle: [
        { title: '用人单位统计', isActive: true },
        { title: '异常单位预警名单', isActive: false },
        { title: '手机号预警名单', isActive: false }
      ],
      mobilePrewarningValue:false,
      refHeight: { value: 0 },
      tableColumns: [],
      tableColumns_1: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '单位名称',
          key: 'enterpriseName'
        },
        {
          title: '就业人数',
          key: 'number'

        },
        {
          title: '操作',
          width: 120,
          slot: 'action',
          align: 'center'

        }
      ],
      tableColumns_2: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '单位电话',
          key: 'dwdh'
        },
        {
          title: '单位名称',
          key: 'dwmc'
        },
        {
          title: '就业人数',
          key: 'num'

        },
        {
          title: '操作',
          width: 120,
          slot: 'action',
          align: 'center'

        }
      ],
      tableData: [],
      tableLoading: false,
      pages: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
        name: ''
      },
      userInfo: JSON.parse(Cookies.get('userInfo')),
      modalPrewarningValue: false,
      modalEarlyWarningKeywords: false,
      loadingPrewarning: false,
      formPrewarningValue: {
        id: '',
        province: 0,
        school: 0,
        isWhitelist: 0
      },
      formEarlyWarningKeywords: {
        alert: ''
      },
      earlyWarningKeywordsList: [],
      loadingDivEarlyWarningKeywords: false,
      exportingAll: false,
      loadingEarlyWarningKeywords: false,
      errorMsg: '测试', //错误提示信息
      showAlert: false, //是否显示错误提示信息
      active: 0,
      mobileThresholdProvince:0
    };
  },
  mounted() {
    if (this.$route.query.type) {
      this.handleClick(this.$route.query.type);
    }

    this.onRestWindow();
    window.addEventListener('resize', this.onRestWindow);
    this.getPageData();
    this.getFormPrewarningValue();
    this.getEarlyWarningKeywordsList();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onRestWindow);
  },
  methods: {
    onRestWindow() {
      let tableColumns= {}
      if (this.active ==2) {
        tableColumns =this.tableColumns_2
      }else {
        tableColumns =this.tableColumns_1
      }
      this.tableColumns = this.restTableCellWidth(tableColumns);
      this.labelWidth140 = this.searchLabelWidth(this.labelWidth140);
    },
    handleSearch() {
      this.pages.pageNumber = 1;
      this.tableLoading = true;
      this.getPageData();
      // if(this.topTitle[0].isActive){
      //     this.pages.name = this.auditNumberName;
      //     getPageDataAuditData(this.pages).then((res) =>{
      //         this.tableData = res.result.records;
      //         this.pages.total = res.result.total || 0;
      //         console.log("用人单位统计数据",res);
      //         this.tableLoading = false;
      //     })
      // }
      // if(this.topTitle[1].isActive){
      //     this.pages.name = this.auditWarningName;
      //     getAllWordsEarlyWarningKeywordsData(this.pages).then((res) =>{
      //         console.log("异常单位预警名单数据",res);
      //         this.tableData = res.result.records;
      //         this.pages.total = res.result.total || 0;
      //         this.tableLoading = false;
      //     })
      //
      // }
    },
    notShowModal(val) {
      if (!val) {
        this.getEarlyWarningKeywordsList();
        this.getPageData();
      }
    },
    exportEmployerStatistics() {
      this.exportingAll = true;
      exportDataAudit().then(res => {
        this.exportingAll = false;
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], { type: 'charset=utf-8' });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '用人单位统计.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      });
    },
    exportDataAuditWarning() {
      this.exportingAll = true;
      exportDataAuditWarning().then(res => {
        this.exportingAll = false;
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], { type: 'charset=utf-8' });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '用人单位统计.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      });
    },
    exportDataAuditNumber() {
      this.exportingAll = true;
      exportDataAuditNumber().then(res => {
        this.exportingAll = false;
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], { type: 'charset=utf-8' });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '用人单位统计.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      });
    },
    getPageData() {
      let pages = this.pages;
      delete pages.total;

      if (this.topTitle[2].isActive) {
        this.tableLoading = true;
        let c = {
          'pageNo': pages.pageNumber,
          'pageSize': pages.pageSize
        };
        this.tableColumns = this.restTableCellWidth(this.tableColumns_2);
        getMobileWarningKeywordsData(c).then((res) => {
          this.tableData = res.result.records;
          this.pages.total = res.result.total || 0;
          this.tableLoading = false;
        });
      } else {
        this.tableColumns = this.restTableCellWidth(this.tableColumns_1);
        if (this.topTitle[0].isActive) {
          this.tableLoading = true;
          pages.name = this.auditNumberName;
          getPageDataAuditData(pages).then((res) => {
            this.tableData = res.result.records;
            this.pages.total = res.result.total || 0;
            this.tableLoading = false;
          });
        }
        if (this.topTitle[1].isActive) {
          this.tableLoading = true;
          pages.name = this.auditWarningName;
          getAllWordsEarlyWarningKeywordsData(pages).then((res) => {
            this.tableData = res.result.records;
            this.pages.total = res.result.total || 0;
            this.tableLoading = false;
          });
        }
      }
    },

    handleClose(row) {
      deleteWordsEarlyWarningKeywordsData({ name: row.word }).then((res) => {
        this.getEarlyWarningKeywordsList();
        this.getPageData();
      });
    },
    getEarlyWarningKeywordsList() {
      this.loadingDivEarlyWarningKeywords = true;
      getWordsEarlyWarningKeywordsData().then(res => {
        this.earlyWarningKeywordsList = res.result;
        this.loadingDivEarlyWarningKeywords = false;
        console.log('预警关键词', res);
      });
    },
    addEarlyWarningKeywordsData() {
      // if(!this.formEarlyWarningKeywords.alert || (this.formEarlyWarningKeywords.alert && !(this.formEarlyWarningKeywords.alert.length>0))){
      //     this.modalEarlyWarningKeywords = false
      // }
      this.loadingEarlyWarningKeywords = true;
      addEarlyWarningKeywordsData(this.formEarlyWarningKeywords).then(res => {
        this.loadingEarlyWarningKeywords = false;
        this.formEarlyWarningKeywords.alert = '';
        // this.modalEarlyWarningKeywords = false;
        if (res.success) {
          this.modalEarlyWarningKeywords = false;
          this.getEarlyWarningKeywordsList();
          this.getPageData();
        } else {
          this.showAlert = true;
          this.errorMsg = res.message;
        }

      });
    },
    getFormPrewarningValue() {
      getProfileData().then(res => {
        this.mobileThresholdProvince = res.result.mobileThresholdProvince
        updateVal(this.formPrewarningValue, res.result);
      });
    },
    setWhiteList() {
      this.$router.push({ name: 'WhiteList' });
    },
    submitFormPrewarningValue() {
      this.loadingPrewarning = true;
      editProfileData(this.formPrewarningValue).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getPageData();
        }
        this.loadingPrewarning = false;
        this.modalPrewarningValue = false;

      });
    },
    submitMobileValue(){
      this.loadingPrewarning = true;
      submitMobileValue(this.mobileThresholdProvince).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getPageData();
        }
        this.loadingPrewarning = false;
        this.mobilePrewarningValue = false;
      });
    },
    checkInfo(row) {
      let query ={},routeData ={}
      if (this.active ==2){
        query = {dwdh:row.dwdh,index: this.active}
        routeData = this.$router.resolve({
          name: 'AataWarningInfo',
          params: { row: row },
          query
        });
        window.open(routeData.href, '_blank');

      }else {
        query =  { enterpriseName: row.enterpriseName, enterpriseCode: row.enterpriseCode, index: this.active }
        routeData = this.$router.resolve({
          name: 'AataWarningInfo',
          params: { row: row },
          query
        });
      }
      window.open(routeData.href, '_blank');

    },
    handleClick(index) {
      this.active = index;
      this.topTitle[index].isActive = true;
      this.topTitle.forEach((item, i) => {
        if (i != index) {
          item.isActive = false;
        }
      });
      this.pages.pageNumber = 1;
      this.getPageData();
    },
    changePage: function(val) {
      this.pages.pageNumber = val;
      this.getPageData();
    },
    changePageSize: function(val) {
      this.pages.pageSize = val;
      this.getPageData();
    }
  }
};
</script>

<style scoped lang="less">
.earlyWarningKeywordsStyle {
  height: 200px;
}

.h-7 {
  height: 7%;
}

.h-92 {
  height: 92%;
}

.itemActive {
  border-bottom: 4px solid #2873f3;
  color: #2873f3;
}

.itemNotActive {
  margin-bottom: 4px;
}

.search-btn {
  width: 60px;
  border-radius: 0 3px 3px 0
}
</style>
